package com.chencq.module.role.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chencq.core.entity.Pager;
import com.chencq.module.role.entity.Role;
import com.chencq.module.role.service.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController {
	
	protected Logger logger = LoggerFactory.getLogger(RoleController.class);
	@Autowired
	RoleService roleService;

	@RequestMapping("/list")
	public String toList(HttpServletRequest request, HttpServletResponse response,Role role,Pager page, ModelMap model) {
		Pager pager = roleService.findPageList(role,page.getPageNo(), page.getPageSize());
		model.put("pager", pager);
		return "role/list";
	}
	
	@RequestMapping("/get/{roleId}")
	@ResponseBody
	public String getById(@PathVariable String roleId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		Role c = (Role) roleService.getById(roleId);
		return c.toString();
	}
	
	@RequestMapping("/delete/{roleId}")
	@ResponseBody
	public String delete(@PathVariable String roleId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		boolean status = false;
		String msg = "";
		Role c = roleService.getById(roleId);
		if (c != null) {
			roleService.delete(c);
			msg = "删除成功";
			status = true;
		} else {
			msg = "删除失败";
		}
		JSONObject json = new JSONObject();
		json.put("status", status);
		json.put("msg", msg);
		return json.toString();
	}
	
	@RequestMapping("/addUI")
	public String toAdd(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "role/edit";
	}
	@RequestMapping("/add")
	public String add(Role c, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		roleService.save(c);
		return "redirect:/role/list";
	}
	
	@RequestMapping("/updateUI/{userId}")
	public String toEdit(@PathVariable String roleId, HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		Role role = roleService.getById(roleId);
		model.put("role", role);
		return "role/edit";
	}
	
	@RequestMapping("/update")
	public String update(Role c, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		roleService.update(c);
		return "redirect:/role/list";
	}
}
